package com.example.myadmin.common.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session，判断session里面的用户信息是否存在，存在放行，不存在拦截
        Object userInfo = request.getSession().getAttribute("userInfo");
        if (userInfo==null){
            log.info("未登录:"+request.getRequestURI());
            //未登录，重定向到登录页  request.getContextPath() :请求的全路径
            response.sendRedirect(request.getContextPath()+"/login");
            return false; //拦截
        }
        log.debug("放行请求："+request.getRequestURI());
        return true;
    }
}
